<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/qgg_blog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/qgg_blog/lib/pace/pace-theme-center-atom.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/qgg_blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/qgg_blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/qgg_blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/qgg_blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/qgg_blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/qgg_blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/qgg_blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="perl,哈希," />










<meta name="description" content="想法来源最近出现了将汇编指令流换算成specman e语言写的激励的需求，于是需要手工一条一条将汇编指令转化成specman e的激励，有时一个汇编文件几百行，简直是要死人了。看了下其实转化过程就是讲汇编指令的每个域进行约束的过程。大多是一个机械化的过程，因此我们可以采用脚本进行转化。对不能覆盖的指令给出提示和标记，等待手工修改，大大减少工作量。 关于转化规则的假设这里我们以一个mov指令为例。假">
<meta property="og:type" content="article">
<meta property="og:title" content="perl哈希数组实现指令表数据结构">
<meta property="og:url" content="https://zhang_de_shuai.gitee.io/qgg_blog/2020/02/14/perl%E5%93%88%E5%B8%8C%E6%95%B0%E7%BB%84%E5%AE%9E%E7%8E%B0%E6%8C%87%E4%BB%A4%E8%A1%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/index.html">
<meta property="og:site_name" content="圭木的博客">
<meta property="og:description" content="想法来源最近出现了将汇编指令流换算成specman e语言写的激励的需求，于是需要手工一条一条将汇编指令转化成specman e的激励，有时一个汇编文件几百行，简直是要死人了。看了下其实转化过程就是讲汇编指令的每个域进行约束的过程。大多是一个机械化的过程，因此我们可以采用脚本进行转化。对不能覆盖的指令给出提示和标记，等待手工修改，大大减少工作量。 关于转化规则的假设这里我们以一个mov指令为例。假">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7777712-b5147054f89808d0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7777712-d529c073673a7c0a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/7777712-5b0111474ab5d1c9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="article:published_time" content="2020-02-14T03:44:48.000Z">
<meta property="article:modified_time" content="2020-02-14T07:48:31.938Z">
<meta property="article:author" content="一只圭工">
<meta property="article:tag" content="perl">
<meta property="article:tag" content="哈希">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/7777712-b5147054f89808d0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/qgg_blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zhang_de_shuai.gitee.io/qgg_blog/2020/02/14/perl哈希数组实现指令表数据结构/"/>





  <title>perl哈希数组实现指令表数据结构 | 圭木的博客</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/qgg_blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">圭木的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/qgg_blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/qgg_blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/qgg_blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/qgg_blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zhang_de_shuai.gitee.io/qgg_blog/qgg_blog/2020/02/14/perl%E5%93%88%E5%B8%8C%E6%95%B0%E7%BB%84%E5%AE%9E%E7%8E%B0%E6%8C%87%E4%BB%A4%E8%A1%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="一只圭工">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/qgg_blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="圭木的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">perl哈希数组实现指令表数据结构</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-02-14T11:44:48+08:00">
                2020-02-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/qgg_blog/categories/%E6%83%B3%E6%B3%95/" itemprop="url" rel="index">
                    <span itemprop="name">想法</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="想法来源"><a href="#想法来源" class="headerlink" title="想法来源"></a>想法来源</h1><p>最近出现了将汇编指令流换算成specman e语言写的激励的需求，于是需要手工一条一条将汇编指令转化成specman e的激励，有时一个汇编文件几百行，简直是<strong>要死人了</strong>。看了下其实转化过程就是讲汇编指令的每个<strong><code>域</code></strong>进行<strong><code>约束</code></strong>的过程。大多是一个机械化的过程，因此我们可以采用脚本进行转化。对不能覆盖的指令给出提示和标记，等待手工修改，大大减少工作量。</p>
<h1 id="关于转化规则的假设"><a href="#关于转化规则的假设" class="headerlink" title="关于转化规则的假设"></a>关于转化规则的假设</h1><p>这里我们以一个<code>mov</code>指令为例。<br>假设<code>mov</code>指令<strong>只</strong>有两种格式，一种是<code>寄存器</code>格式，一种是<code>立即数</code>格式。如下所示：</p>
<figure class="highlight avrasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">mov</span>  <span class="built_in">r1</span>,<span class="built_in">r2</span><span class="comment">;//寄存器格式，将r2的数据放到r1中。</span></span><br><span class="line"><span class="keyword">mov</span>  <span class="built_in">r1</span>,<span class="meta">#0x55;//立即数格式，将0x55放入r1中。</span></span><br></pre></td></tr></table></figure>
<p>将这两条指令转化成specman e语言的激励如下</p>
<figure class="highlight x86asm"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">do</span> reg <span class="keyword">mov</span> inst keeping &#123;</span><br><span class="line"><span class="meta">        .src0</span>==<span class="built_in">r2</span><span class="comment">;</span></span><br><span class="line"><span class="meta">        .oreg</span>==<span class="built_in">r1</span><span class="comment">;</span></span><br><span class="line"> &#125;<span class="comment">;</span></span><br><span class="line"><span class="built_in">do</span> imm <span class="keyword">mov</span> inst keeping &#123;</span><br><span class="line"><span class="meta">          .dis</span>==<span class="number">0x55</span><span class="comment">;</span></span><br><span class="line"><span class="meta">          .oreg</span>==<span class="built_in">r1</span><span class="comment">;</span></span><br><span class="line">&#125;；</span><br></pre></td></tr></table></figure>
<p>其中<code>do keeping</code>语句是e语言的关键词。剩下的都是预定义的和指令集有关的一些数据结构的生成。我们要做的就是对数据结构中一些未定义的变量进行约束。上面未定义的部分是<code>src0 oreg dis</code>,分别代表<code>源操作数1 目标操作寄存器 立即数</code>，根据指令集，还会有其他未定义字段，在此只举例一部分。</p>
<h1 id="问题分析"><a href="#问题分析" class="headerlink" title="问题分析"></a>问题分析</h1><p>约定了转化关系，那么我们将任务分解。</p>
<hr>
<ol>
<li>首先读取汇编文件的每一行指令，对指令进行分解。分解得出<code>助记符 操作数1 操作数2 操作数3 ...</code>。关于如何分解出指令不同的域，可以参考另一片文章<a href="https://www.jianshu.com/p/27cd5302ccac" target="_blank" rel="noopener" title="Title">用perl脚本获取天气</a>介绍的split函数，再结合一些正则匹配就可以对指令集做出分类分解。</li>
<li>得到了指令的各个域，那么我们就针对汇编指令格式做一张表格，表格里存着每个操作数和specman e语言编写的指令表未定字段的对应关系。在此我们按汇编指令的操作数顺序分类。对于<code>mov</code>指令，第一个操作数对应specman e指令表的未定字段<code>oreg</code>，第二个操作数对应<code>src0</code>。对不同的指令来说，汇编的操作数对应specman e的未定的段是不同的，perl的这张表就记录每条指令的对应关系。</li>
<li>根据分解的汇编指令的各个域，去查找表对应的字段，进行填写后格式化输出到一个文件中。</li>
</ol>
<hr>
<h1 id="指令表的数据结构"><a href="#指令表的数据结构" class="headerlink" title="指令表的数据结构"></a>指令表的数据结构</h1><p>指令表我们采用哈希数组存储。在此我们利用哈希数组实现一个复杂的数据结构，哈希中的哈希。在此我参考这篇文章实现《<a href="http://blog.csdn.net/sunshoupo211/article/details/33731859" target="_blank" rel="noopener">Perl入门（八）Perl的复杂数据结构</a>》。于是得到以下数据结构：</p>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/perl </span></span><br><span class="line"><span class="keyword">use</span> warnings</span><br><span class="line"><span class="keyword">our</span> %inst=();</span><br><span class="line">$inst&#123;<span class="string">'ldi'</span>&#125;=&#123;</span><br><span class="line">    <span class="string">'op_num'</span>=&gt;<span class="number">3</span>,</span><br><span class="line">    <span class="string">'op1'</span>=&gt;<span class="string">'oreg'</span>,</span><br><span class="line">    <span class="string">'op2'</span>=&gt;<span class="string">'dis'</span>,</span><br><span class="line">    <span class="string">'op3'</span>=&gt;<span class="string">'src1'</span></span><br><span class="line">&#125;;</span><br><span class="line">$inst&#123;<span class="string">'mov'</span>&#125;=&#123;</span><br><span class="line">    <span class="string">'op_num'</span>=&gt;<span class="number">2</span>,</span><br><span class="line">    <span class="string">'reg'</span>=&gt;&#123;</span><br><span class="line">            <span class="string">'op1'</span>=&gt;<span class="string">'oreg'</span>,</span><br><span class="line">            <span class="string">'op2'</span>=&gt;<span class="string">'src0'</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="string">'imm'</span>=&gt;&#123;</span><br><span class="line">            <span class="string">'op1'</span>=&gt;<span class="string">'oreg'</span>,</span><br><span class="line">            <span class="string">'op2'</span>=&gt;<span class="string">'dis'</span>,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>此文件保存为<code>inst.pl</code>，我们可以认为这是一个多级列表。第一级的是<code>%inst</code>哈希表引用，第二级是指令<code>助记符</code>，可以任意扩展添加指令。第三级是关于指令的一些数据，<code>op_num</code>指示当前指令需要的操作数个数，可在主程序中获取该键值从而对指令合法性<em>(能检查出分解计算的操作数个数不对的情况，这时候不是分解 过程出错就是源指令出错)</em>进行判断。<code>reg</code>指示指令的寄存器格式和specman e的指令表达的对应关系。同理<code>imm</code>也是如此。该数据结构的实现方便与以后指令集的更改做兼容，要实现对新指令的转化只需要在表中添加对应项即可，无需修改主程序。如需要适应更复杂的指令情况则需要在表中添加对应表项进行查询判断。</p>
<h1 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h1><p>为了方便测试，我们将实际指令的各个段做人为的初始化，在实际处理中，各个字段需要从指令分解得到。<br>为了方便管理指令表使用单独一个文件保存，在主程序开头需要将指令文件导入。要在一个perl脚本中引用另一个脚本的函数和变量有两种方式：</p>
<ol>
<li>将需要导入的文件编译成perl的模块文件，使用<code>use</code>语句导入模块。</li>
<li>在开头使用<code>require</code>语句导入另一个文件，要注意变量的作用域问题。</li>
</ol>
<p>在此为了方便修改，我是用<code>require</code>方式。测试代码<code>main.pl</code>如下：</p>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/perl </span></span><br><span class="line"><span class="keyword">use</span> strict;</span><br><span class="line"><span class="keyword">use</span> warnings;</span><br><span class="line"><span class="keyword">require</span> <span class="string">"inst.pl"</span>;</span><br><span class="line"><span class="keyword">our</span> %inst;</span><br><span class="line"><span class="keyword">open</span> RESFILE,<span class="string">"&gt;&gt;res.txt"</span> <span class="keyword">or</span> <span class="keyword">die</span> <span class="string">"can't open :$!"</span>;</span><br><span class="line"><span class="keyword">my</span> $zhiling=<span class="string">'mov'</span>;</span><br><span class="line"><span class="keyword">my</span> $op1=<span class="string">'r2'</span>;</span><br><span class="line"><span class="keyword">my</span> $op2=<span class="string">'r3'</span>;</span><br><span class="line"><span class="keyword">my</span> $op3=<span class="string">'r4'</span>;</span><br><span class="line"><span class="keyword">my</span> $inst_type=<span class="string">'reg'</span>;</span><br><span class="line"><span class="keyword">if</span>(<span class="keyword">exists</span> $inst&#123;$zhiling&#125;-&gt;&#123;$inst_type&#125;)&#123;<span class="comment">#判断指令类型是否存在</span></span><br><span class="line">    <span class="keyword">if</span>($inst&#123;$zhiling&#125;-&gt;&#123;<span class="string">'op_num'</span>&#125;==<span class="number">2</span>)&#123;<span class="comment">#确定操作数个数</span></span><br><span class="line">            <span class="keyword">print</span>   RESFILE <span class="string">"do $inst_type $zhiling inst keeping &#123;\n"</span>.</span><br><span class="line">                    <span class="string">".$inst&#123;$zhiling&#125;-&gt;&#123;$inst_type&#125;-&gt;&#123;'op1'&#125;==$op1;\n"</span>.<span class="comment">#约束操作数1</span></span><br><span class="line">                    <span class="string">".$inst&#123;$zhiling&#125;-&gt;&#123;$inst_type&#125;-&gt;&#123;'op2'&#125;==$op2;\n"</span>.<span class="comment">#约束操作数2</span></span><br><span class="line">                    <span class="string">"&#125;;\n"</span>;</span><br><span class="line">            &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">close</span> RESFILE;</span><br></pre></td></tr></table></figure>
<p>测试代码只实现了两个操作数的输出，并人为初始化了指令的各个域，可根据实际来定。适应更多情况则添加<code>if</code>语句进行扩展。</p>
<h1 id="测试结果"><a href="#测试结果" class="headerlink" title="测试结果"></a>测试结果</h1><p><img src="https://upload-images.jianshu.io/upload_images/7777712-b5147054f89808d0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="寄存器格式测试结果"></p>
<p>在<code>main.pl</code>中我们将处理结果输出到<code>res.txt</code>中，由结果来看实现了转化功能。<br>我们再尝试初始化为<code>立即数格式</code>，看看测试结果。<br><img src="https://upload-images.jianshu.io/upload_images/7777712-d529c073673a7c0a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="初始化为立即数"><br><img src="https://upload-images.jianshu.io/upload_images/7777712-5b0111474ab5d1c9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="立即数格式测试结果"><br>由图片可见成功向文件添加了立即数格式的转化结果。<br>主体部分就是这样子，在程序中循环执行，那么无论是多少行汇编都很轻松转化。为了更人性化，还要增加一些提示，毕竟谁也不能保证程序100%正确运行，在不能处理的指令行做出固定标记以供查阅修改。<br>以后看情况在继续分析指令分解的部分。复杂的指令分解需要参考汇编的<strong>词法分析器</strong>。</p>

      
    </div>
    
    
    
	<div>
	      
	        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/qgg_blog/2020/02/14/perl%E5%93%88%E5%B8%8C%E6%95%B0%E7%BB%84%E5%AE%9E%E7%8E%B0%E6%8C%87%E4%BB%A4%E8%A1%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">perl哈希数组实现指令表数据结构</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 一只圭工 的个人博客">一只圭工</a></p>
  <p><span>发布时间:</span>2020年02月14日 - 11:02</p>
  <p><span>最后更新:</span>2020年02月14日 - 15:02</p>
  <p><span>原始链接:</span><a href="/qgg_blog/2020/02/14/perl%E5%93%88%E5%B8%8C%E6%95%B0%E7%BB%84%E5%AE%9E%E7%8E%B0%E6%8C%87%E4%BB%A4%E8%A1%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" title="perl哈希数组实现指令表数据结构">https://zhang_de_shuai.gitee.io/qgg_blog/2020/02/14/perl%E5%93%88%E5%B8%8C%E6%95%B0%E7%BB%84%E5%AE%9E%E7%8E%B0%E6%8C%87%E4%BB%A4%E8%A1%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://zhang_de_shuai.gitee.io/qgg_blog/2020/02/14/perl%E5%93%88%E5%B8%8C%E6%95%B0%E7%BB%84%E5%AE%9E%E7%8E%B0%E6%8C%87%E4%BB%A4%E8%A1%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>


	      
	</div>

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/qgg_blog/tags/perl/" rel="tag"> <i class="fa fa-tag"></i> perl</a>
          
            <a href="/qgg_blog/tags/%E5%93%88%E5%B8%8C/" rel="tag"> <i class="fa fa-tag"></i> 哈希</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/qgg_blog/2020/02/14/%E7%94%A8perl%E8%84%9A%E6%9C%AC%E8%8E%B7%E5%8F%96%E5%A4%A9%E6%B0%94/" rel="prev" title="用perl脚本获取天气">
                用perl脚本获取天气 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/qgg_blog/images/head.jpg"
                alt="一只圭工" />
            
              <p class="site-author-name" itemprop="name">一只圭工</p>
              <p class="site-description motion-element" itemprop="description">我想拥有权利，不是凌驾于别人之上的权利，而是凌驾于自然和科技命运之上的权利，我只想知道事物的运作规律</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/qgg_blog/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/qgg_blog/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/qgg_blog/tags/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/zhang_de_shuai" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-github"></i>Gitee</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#想法来源"><span class="nav-number">1.</span> <span class="nav-text">想法来源</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#关于转化规则的假设"><span class="nav-number">2.</span> <span class="nav-text">关于转化规则的假设</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#问题分析"><span class="nav-number">3.</span> <span class="nav-text">问题分析</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#指令表的数据结构"><span class="nav-number">4.</span> <span class="nav-text">指令表的数据结构</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#测试"><span class="nav-number">5.</span> <span class="nav-text">测试</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#测试结果"><span class="nav-number">6.</span> <span class="nav-text">测试结果</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一只圭工</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">3.2k</span>
  
</div>

<!--
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>

-->


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      人次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/qgg_blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/qgg_blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/qgg_blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/qgg_blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/qgg_blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/qgg_blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/qgg_blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/qgg_blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/qgg_blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/qgg_blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('-1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
<script type="text/javascript" src="/js/src/clicklove.js"></script>
